<script setup lang="ts">
import type { DropdownOption, DropdownProps } from 'naive-ui'
import { NButton, NDropdown } from 'naive-ui'
import { type ChangeOptions, useTable } from '@/hooks/useTable.ts'
import { usePageConfig } from './config/index.ts'
import roleApi from '@/service/api/setting/role'
import postApi from '@/service/api/setting/post'
import departmentApi from '@/service/api/setting/department'
import NTableBuilder from '@/components/NTableBuilder/index.vue'

defineOptions({
  name: 'UserPage',
})
/**
 * 页面全局参数
 * */
const optionsState = reactive({
  routeList: [],
  oldOptions: {
    id: null,
    weight: 0,
  },
  allTree: [],
  treeList: [],
  postList: [],
})
provide('optionsState', optionsState)
/**
 * 获取页面配置
 * */
const pageConfig = usePageConfig()
const addChange = (options: ChangeOptions) => {
  if (options.key === 'dept') {
    getDepartMent()
  }
}
const { table, tableProps, action } = useTable(pageConfig, {
  options: {
    optionsState,
  },
  change: addChange,
})

/**
 * 右键菜单
 * */
const menuState = reactive<DropdownProps>({
  show: false,
  x: 0,
  y: 0,
  options: [],
  onClickoutside: () => {
    menuState.show = false
  },
  onSelect: (key: string) => {
    menuState.show = false
    switch (key) {
      case 'add':
        action.dept({
          parentId: optionsState.oldOptions.id,
          name: '',
          sortOrder: 1,
        })
        break
      case 'edit':
        action.dept({
          ...optionsState.oldOptions,
          deptId: optionsState.oldOptions.id,
          sortOrder: optionsState.oldOptions.weight,
        })
        break
      default:
        msgUtil.$dialog.warning({
          title: '温馨提示',
          content: '确认要删除此部门吗？',
          positiveText: '确定',
          negativeText: '取消',
          onPositiveClick: async () => {
            const { code, msg } = await departmentApi.del({
              ids: [optionsState.oldOptions.id],
            })
            if (code !== 0) {
              msgUtil.$message.error(msg)
              return
            }
            getDepartMent()
          },
        })
        break
    }
  },
})

/**
 * 树形菜单
 * */
const nodeProps = ({ option }) => {
  return {
    onContextmenu(e: MouseEvent): void {
      optionsState.oldOptions = toRaw(option)
      const optioAuth = []
      if (commonUnit.auth('sys_dept_add')) {
        optioAuth.push({
          label: '添加',
          key: 'add',
        })
      }
      if (commonUnit.auth('sys_dept_edit')) {
        optioAuth.push({
          label: '编辑',
          key: 'edit',
        })
      }
      if (commonUnit.auth('sys_dept_del')) {
        optioAuth.push({
          label: '删除',
          key: 'del',
        } as DropdownOption)
      }
      menuState.options = optioAuth
      menuState.x = e.clientX
      menuState.y = e.clientY
      menuState.show = true
      e.preventDefault()
    },
  }
}
const treeSelectChange = (e) => {
  if (e.length > 0) {
    departmentApi.detail(e[0] as number).then(({ data }) => {
      table.tableInfo.queryForm.deptId = data.deptId
      table.queryData()
    })
  } else {
    table.tableInfo.queryForm.deptId = null
    table.queryData()
  }
}

const deptState = reactive<{
  keyword: string
  loading: boolean
  timer
}>({
  keyword: '',
  loading: false,
  timer: null,
})
const handleInput = () => {
  if (deptState.timer) {
    clearTimeout(deptState.timer)
  }
  deptState.timer = setTimeout(() => {
    getDepartMent()
  }, 300)
}
const getDepartMent = async () => {
  const { data } = await departmentApi.list({
    deptName: deptState.keyword,
  })
  if (!deptState.keyword) {
    optionsState.allTree = data
  }
  optionsState.treeList = data
}

const getOptionsState = () => {
  postApi.allList().then(({ data }) => {
    optionsState.postList = data
  })
  roleApi.allList().then(({ data }) => {
    optionsState.routeList = data
  })
}

onMounted(() => {
  getDepartMent()
  getOptionsState()
})
</script>
<template>
  <div class="user-page">
    <div class="user-page-main">
      <div class="depart">
        <div class="depart-main">
          <div class="search">
            <div class="mb10">
              <n-button v-auth="'sys_dept_add'" type="primary" @click="action.dept()">
                <i class="esayIcon esayIcon-tianjiawenjianjia"></i>
              </n-button>
            </div>
            <n-input
              v-model:value="deptState.keyword"
              :loading="deptState.loading"
              placeholder="搜索"
              @input="handleInput"
            >
              <template #prefix>
                <n-icon>
                  <i class="esayIcon esayIcon-sousuo"></i>
                </n-icon>
              </template>
            </n-input>
          </div>

          <div class="tree-list">
            <n-tree
              block-line
              :data="optionsState.treeList"
              :node-props="nodeProps"
              key-field="id"
              label-field="name"
              children-field="children"
              @update:selected-keys="treeSelectChange"
            />
          </div>
        </div>
      </div>

      <n-table-builder v-model="table.tableInfo" v-bind="tableProps" />
    </div>
    <n-dropdown trigger="manual" placement="bottom-start" v-bind="menuState" />
  </div>
</template>

<style lang="scss" scoped>
.user-page {
  height: 100%;

  &-main {
    display: flex;
    height: 100%;
  }

  .depart {
    background: var(--yang-menu-navtop-bg-color);
    margin: 16px 0 16px 16px;
    border-radius: 5px;
    min-width: 200px;
    position: relative;

    &-main {
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      display: flex;
      flex-direction: column;
      padding: 14px;

      .tree-list {
        margin-top: 24px;
        flex: 1;
        overflow: scroll;
      }
    }
  }

  .list-page {
    flex: 1;
  }
}
</style>
